package com.mybatis.plugin;

import org.apache.commons.codec.binary.Base64;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-03-24 13:56:39
 */
@Intercepts({
        // 执行查询之后，对结果集进行修改
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class CustomerInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(CustomerInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Method method = invocation.getMethod();
        Object[] args = invocation.getArgs();
        Object target = invocation.getTarget();
        logger.info("method = {}, args = {}, target = {}",
                method, Arrays.toString(args), target);
        logger.info("arg1 = {}, type = {}", args[1], args[1].getClass());

        List<?> proceed = (List<?>) invocation.proceed();
        logger.info("proceed = {}", proceed);

        for (Object o : proceed) {
            Field[] fields = o.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                boolean isPassword = field.getName().equals("password");
                if (isPassword) {
                    // 得到的是加密数据
                    String s = (String) field.get(o);
                    byte[] bytes = Base64.decodeBase64(s);
                    field.set(o, new String(bytes));
                }
            }
        }

        return proceed;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        String arg1 = properties.getProperty("arg1");
        String arg2 = properties.getProperty("arg2");
        logger.info("arg1 = {} , arg2 = {}", arg1, arg2);
    }
}
